{% extends "base.html" %}

{% block content %}
<h1>Estadísticas del marcador</h1><br/>

<p><label for="fecini">Filtrar resultados desde la fecha</label> <input type="text" id="fecini" />
<label for="fecfin">hasta</label> <input type="text" id="fecfin" /> <button class="botonazul" id="btnfiltrar">Filtrar</button></p>
<br/><br/>

<h2 style="text-align: center;">Total Marcaciones</h2>
<table id="dataTotalRec" style="text-align: center;">
	<thead>
		<tr>
			<th></th>
			<th>Marcaciones Corretas</th>
			<th>Marcaciones No Factibles</th>
			<th>Total</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<th>Cantidad</th>
			<td id="totalRec"></td>
			<td id="totalNoRec"></td>
			<td id="totalLogs"></td>
		</tr>
	</tbody>
</table>
<br/>
<div id="pieTotalRec" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<br/><br/><br/><br/><br/>

<h2 style="text-align: center;">Marcaciones Categorizadas</h2>
<table id="dataCateMarc" style="text-align: center;">
	<thead>
		<tr>
			<th></th>
			<th>Primera</th>
			<th>Segunda</th>
			<th>Tercera</th>
			<th>Cuarta</th>
			<th>Quinta</th>
			<th>TOTAL</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<th>Cantidad</th>
			<td id="totalRec1"></td>
			<td id="totalRec2"></td>
			<td id="totalRec3"></td>
			<td id="totalRec4"></td>
			<td id="totalRec5"></td>
			<td id="totalLogsCate"></td>
		</tr>
	</tbody>
</table>
<br/>
<div id="pieCateNumber" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<br/><br/><br/><br/><br/>

<h2 style="text-align: center;">Distancias MIN-MAX Categorizadas</h2>
<table id="dataMinMaxDistannce" style="text-align: center;">
	<thead>
		<tr>
			<th></th>
			<th>DISTANCIA MÍNIMA</th>
			<th>DISTANCIA MÁXIMA</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<th>Primera</th>
			<td id="min1"></td>
			<td id="max1"></td>
		</tr>
		<tr>
			<th>Segunda</th>
			<td id="min2"></td>
			<td id="max2"></td>
		</tr>
		<tr>
			<th>Tercera</th>
			<td id="min3"></td>
			<td id="max3"></td>
		</tr>
		<tr>
			<th>Cuarta</th>
			<td id="min4"></td>
			<td id="max4"></td>
		</tr>
		<tr>
			<th>Quinta</th>
			<td id="min5"></td>
			<td id="max5"></td>
		</tr>
	</tbody>
</table>
<br/>
<div id="minmaxChartCol" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<br/><br/><br/><br/><br/>

<h2 style="text-align: center;">Distancias de Marcaciones</h2>
<div id="distAreaChart" style="min-width: 350px; height: 350px; margin: 0 auto"></div>
<br/><br/><br/><br/><br/>
{% end %}

{% block scripts %}
<script src="/static/js/libs/highcharts-all.js" type="text/javascript"></script>

<script>
jQuery(function($){
	var jsonData = jQuery.parseJSON('{{ jsondata }}');
	var fecIni = null, fecFin = null;

	if(jsonData.filterDateIni){
		fecIni = new Date(jsonData.filterDateIni);
	}

	if(jsonData.filterDateFin){
		fecFin = new Date(jsonData.filterDateFin);
	}

	$(function() {
		$('#fecini, #fecfin').datepicker({
			showOn: "both",
			beforeShow: customRange,
			dateFormat: "yy-m-dd"
		});

		$("#btnfiltrar").click(function(event){
			event.preventDefault();
			window.location.href = "/statistics?fecini=" + $('#fecini').val() + "&fecfin=" + $('#fecfin').val();
		});
	});

	function customRange(input){
		if (input.id == 'fecfin') {
			var minDate = new Date($('#fecini').val());
			minDate.setDate(minDate.getDate() + 1);
			return {minDate: minDate};
		}

		return {}
	}

	$("#totalRec").text(jsonData.totalRec);
	$("#totalNoRec").text(jsonData.totalNoRec);
	$("#totalLogs").text(jsonData.totalLogs);

	if(jsonData.totalRec > 0 || jsonData.totalNoRec > 0 || jsonData.totalLogs > 0)
		drawPieTotalRec(jsonData.totalRec, jsonData.totalNoRec);

	$("#totalRec1").text(jsonData.totalRec1);
	$("#totalRec2").text(jsonData.totalRec2);
	$("#totalRec3").text(jsonData.totalRec3);
	$("#totalRec4").text(jsonData.totalRec4);
	$("#totalRec5").text(jsonData.totalRec5);
	$("#totalLogsCate").text(jsonData.totalRec);

	if(jsonData.totalRec1 > 0 || jsonData.totalRec2 > 0 || jsonData.totalRec3 > 0 || jsonData.totalRec4 > 0 || jsonData.totalRec5 > 0)
		drawPieCateNumber(jsonData.totalRec1, jsonData.totalRec2, jsonData.totalRec3, jsonData.totalRec4, jsonData.totalRec5);

	$("#min1").text(jsonData.min1); $("#max1").text(jsonData.max1);
	$("#min2").text(jsonData.min2); $("#max2").text(jsonData.max2);
	$("#min3").text(jsonData.min3); $("#max3").text(jsonData.max3);
	$("#min4").text(jsonData.min4); $("#max4").text(jsonData.max4);
	$("#min5").text(jsonData.min5); $("#max5").text(jsonData.max5);

	if(jsonData.min1 > 0 || jsonData.min2 > 0 || jsonData.min3 > 0 || jsonData.min4 > 0 || jsonData.min5 > 0)
		drawMinMaxColumnChart();

	if(jsonData.distances.length > 0)
		drawDistancesAreaChart(jsonData.distances, jsonData.intervalDist, new Date(jsonData.minDateDist));

	// Radialize the colors
	Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function(color) {
		return {
			radialGradient: { cx: 0.5, cy: 0.3, r: 0.7 },
			stops: [
				[0, color],
				[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
			]
		};
	});

	function drawPieTotalRec(correctas, nofactibles){
	    new Highcharts.Chart({
            chart: {
				renderTo: 'pieTotalRec',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
				animation: {
					duration: 3000,
					easing: 'easeOutBounce'
				}
            },
            title: {
                text: ''
            },
            tooltip: {
        	    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function() {
                            return '<b>'+ this.point.name +'</b>: '+ this.percentage.toFixed(2) + ' %';
                        }
                    }
                }
            },
            series: [{
                type: 'pie',
                name: 'Marcaciones',
                data: [
                    {
                        name: 'Marcaciones Correctas',
                        y: correctas,
                        sliced: true,
                        selected: true
                    },
                    ['No Factibles', nofactibles]
                ]
            }]
        });
	}

	function drawPieCateNumber(c1, c2, c3, c4, c5){
        new Highcharts.Chart({
            chart: {
				renderTo: 'pieCateNumber',
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
				animation: {
					duration: 3000,
					easing: 'easeOutBounce'
				}
            },
            title: {
                text: ''
            },
            tooltip: {
        	    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        formatter: function() {
                            return '<b>'+ this.point.name +'</b>: '+ this.percentage.toFixed(2) + ' %';
                        }
                    }
                }
            },
            series: [{
                type: 'pie',
                name: 'Marcaciones',
                data: [
                    {
                        name: 'Primera',
                        y: c1,
                        sliced: true,
                        selected: true
                    },
                    ['Segunda', c2],
                    ['Tercera', c3],
                    ['Cuarta', c4],
                    ['Quinta', c5]
                ]
            }]
        });
	}

	function drawMinMaxColumnChart(){
        new Highcharts.Chart({
            chart: {
				type: 'column',
				renderTo: 'minmaxChartCol',
				plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
				animation: {
					duration: 3000,
					easing: 'easeOutBounce'
				}
            },
            data: {
				table: document.getElementById('dataMinMaxDistannce')
			},
			title: {
				text: ''
			},
			yAxis: {
				allowDecimals: false,
				title: {
					text: 'Distancia'
				}
			},
			tooltip: {
				formatter: function() {
					return '<b>'+ this.series.name +'</b><br/>'+ this.y.toFixed(2) +' '+ this.x.toLowerCase();
				}
			}
        });
	}

	function drawDistancesAreaChart(distances, intervalDist, iniDate){
		new Highcharts.Chart({
            chart: {
				renderTo: 'distAreaChart',
				zoomType: 'x',
                spacingRight: 20,
				animation: {
					duration: 3000,
					easing: 'easeOutBounce'
				}
            },
            title: {
                text: ''
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                    'Para hacer zoom-in, click y arrastre en el área' :
                    'Toque el gráfico para hacer zoom-in'
            },
            xAxis: {
                type: 'datetime',
                maxZoom: 24 * 60 * 60 * 1000,
                title: {
                    text: null
                }
            },
            yAxis: {
                title: {
                    text: 'Distancias'
                }
            },
            tooltip: {
                shared: true
            },
            legend: {
                enabled: false
            },
            plotOptions: {
                area: {
                    fillColor: {
                        linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
                        stops: [
                            [0, Highcharts.getOptions().colors[0]],
                            [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                        ]
                    },
                    lineWidth: 1,
                    marker: {
                        enabled: false
                    },
                    shadow: false,
                    states: {
                        hover: {
                            lineWidth: 1
                        }
                    },
                    threshold: null
                }
            },

            series: [{
                type: 'area',
                name: 'Distancias',
                pointInterval: intervalDist,
                pointStart: iniDate.getTime(),
                data: distances
            }]
		});
	}
});
</script>
{% end %}